package com.zhny.aiot.infrared.ray.plugin.core;

import com.zhny.aiot.infrared.ray.plugin.factory.IinfraredRayFactory;
import com.zhny.aiot.infrared.ray.plugin.factory.imp.PassInOutFactory;
import com.zhny.aiot.infrared.ray.plugin.factory.imp.StatisticsFactory;
import com.zhny.aiot.infrared.ray.plugin.model.InfraredRayStoreEntry;
import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.model.IRequestMessage;
import com.zhny.aiot.plugin.modbus.ModemEngine;
import com.zhny.aiot.plugin.modbus.device.ModemConfig;
import com.zhny.aiot.plugin.modbus.device.modbus.ModbusNumDevice;
import com.zhny.aiot.plugin.modbus.handler.model.ModemResponseMessage;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.TaskEntity;
import io.netty.buffer.ByteBufUtil;

public class InfraredRayDevice extends ModbusNumDevice<InfraredRayStoreEntry> {
    public InfraredRayDevice(ModemEngine engine, IDeviceFactory<ModemConfig> factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super(engine, factory, centerFacilities, entity);
    }

    @Override
    protected IRequestMessage getCommand(TaskEntity taskEntity) {
        return getFactory().getRequestMessage(getConfig());
    }

    @Override
    public InfraredRayStoreEntry decode(ModemResponseMessage modemResponseMessage) {
        IinfraredRayFactory factory;
        logger.info("read modbus code [{}] [{}] [{}] [{}]",modemResponseMessage.getKey(),
                modemResponseMessage.getFunction(),
                modemResponseMessage.getSize(),ByteBufUtil.hexDump(modemResponseMessage.getData()));
        if(modemResponseMessage.getSize() == 14) {
            factory=new StatisticsFactory();
        }else if(modemResponseMessage.getSize() == 13) {
            factory=new PassInOutFactory();
        }else {
            return null;
        }
        return factory.onDecode(modemResponseMessage.getData());
    }

    @Override
    public boolean checkError(ModemResponseMessage modemResponseMessage) {
        return modemResponseMessage.getFunction() == 0x03;
    }

    @Override
    protected void disposable() {

    }
}
